//
//  BusController.m
//  EagleEye
//
//  Created by 18_李明明 on 15-1-20.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "BusController.h"
#import "CityViewController.h"
#import "NetHander.h"
#import "RoadViewController.h"
#import "PlatViewController.h"
#import "ChangeController.h"
#import "FirstPageCell.h"
#import "SecondPageCell.h"
#import "ThirdPageCell.h"
#import "DataBaseHandler.h"
@interface BusController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>
{
    UIAlertView *alert;
}
@property (nonatomic, strong) UIButton *cancle;
@property (nonatomic, strong) UISegmentedControl *segment;
// 创建一个scrollview
@property (nonatomic, strong) UIScrollView *busScrollView;
// 在第一页创建一个输入框
@property (nonatomic, strong) UITextField *roadThread;
// 第一个页面创建一个tabview
@property (nonatomic, strong) UITableView *roadTableView;
@property (nonatomic, strong) UIButton *selectCity;
// 一个用来保存线路信息的数组
@property (nonatomic, strong) NSArray *roadArr;

// 在第二页创建一个tableview
@property (nonatomic, strong) UITableView *changeTableview;
// 创建两个textfield
@property (nonatomic, strong) UITextField *from;
@property (nonatomic, strong) UITextField *to;
//第二页创建一个查找按钮
@property (nonatomic, strong) UIButton *changeQuery;
// 创建一个用来存公交换乘的数组
@property (nonatomic, strong) NSArray *roadThreads;

// 第三页 创建一个输入框
@property (nonatomic, strong) UITextField *plat;
@property (nonatomic, strong) UIButton *platSelect;
@property (nonatomic, strong) UITableView *platTableView;
@property (nonatomic, strong) NSArray *platArr;
//数据库
@property (nonatomic, strong) DataBaseHandler *dataBase;

@end

@implementation BusController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.roadArr = [NSArray array];
        self.roadThreads = [NSArray array];
        self.platArr = [NSArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    self.dataBase = [DataBaseHandler shareInstance];
    [self.dataBase openDB];
    [self creatControl];
    [self firstPage];
    [self secondPage];
    [self thirdPage];
}
- (void)creatControl
{
    // 创建一个数组用来放功能
    NSArray *arr = [NSArray arrayWithObjects:@"线路查询", @"换乘", @"站台查询", nil];
    // 根据这个数组初始化segment
    self.segment = [[UISegmentedControl alloc] initWithItems:arr];
    self.segment.frame = CGRectMake(0, 20, WIDTH, 40);
    [self.view addSubview:self.segment];
    [self.segment addTarget:self action:@selector(targetSegment:) forControlEvents:UIControlEventValueChanged];
    self.segment.selectedSegmentIndex = 1;
    // 创建一个scrollview
    self.busScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 60, WIDTH, HEIGHT - 100)];
    self.busScrollView.contentSize = CGSizeMake(WIDTH * 3, 0);
    self.busScrollView.contentOffset = CGPointMake(WIDTH, 0);
    self.busScrollView.pagingEnabled = YES;
//    self.busScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.busScrollView];
    self.busScrollView.delegate = self;
   
    // 添加一个返回的按钮
    self.cancle = [UIButton buttonWithType:UIButtonTypeSystem];
    self.cancle.frame = CGRectMake(0, HEIGHT - 40, 40, 30);
//    [self.cancle setTitle:@"返回" forState:UIControlStateNormal];
    [self.cancle setBackgroundImage:[UIImage imageNamed:@"cancle.png"] forState:UIControlStateNormal];
    [self.view addSubview:self.cancle];
    [self.cancle addTarget:self action:@selector(targetCancle:) forControlEvents:UIControlEventTouchUpInside];
}
// 返回按钮方法
- (void)targetCancle:(UIButton *)cancle
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark 第一页
// 第一页
- (void)firstPage
{
    
    // 创建一个选择城市的按钮
    self.selectCity = [UIButton buttonWithType:UIButtonTypeSystem];
    self.selectCity.frame = CGRectMake(0, 10, 80, 30);
    [self.selectCity setTitle:self.str forState:UIControlStateNormal];
    self.selectCity.backgroundColor = [UIColor cyanColor];
    [self.busScrollView addSubview:self.selectCity];
    [self.selectCity addTarget:self action:@selector(targetSelect:) forControlEvents:UIControlEventTouchUpInside];
     // 创建一个输入框
    self.roadThread = [[UITextField alloc] initWithFrame:CGRectMake(80, 10, WIDTH - 90, 30)];
    self.roadThread.placeholder = @"亲，您要查几路呢？";
    self.roadThread.borderStyle = UITextBorderStyleRoundedRect;
    [self.busScrollView addSubview:self.roadThread];
    // 创建一个查找按钮
    UIButton *query = [UIButton buttonWithType:UIButtonTypeSystem];
    query.frame = CGRectMake(0, 40, WIDTH, 40);
    [query setTitle:@"查找" forState:UIControlStateNormal];
    [self.busScrollView addSubview:query];
    [query addTarget:self action:@selector(targetQuery:) forControlEvents:UIControlEventTouchUpInside];
    // 创建一个tableview用来显示线路信息
    self.roadTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 90, WIDTH, HEIGHT - 175) style:UITableViewStyleGrouped];
    self.roadTableView.delegate = self;
    self.roadTableView.dataSource = self;
    [self.busScrollView addSubview:self.roadTableView];
    self.roadTableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"busthread.jpg"]];
    // 判断是不是从历史那页跳过来
    if (self.line.length != 0) {
        [self.cancle removeFromSuperview];
        self.roadThread.text = self.line;
        self.segment.selectedSegmentIndex = 0;
        self.busScrollView.contentOffset = CGPointMake(0, 0);
            [self firstPageSelect];
        [self.cancle removeFromSuperview];
        self.roadTableView.frame = CGRectMake(0, 90, WIDTH, HEIGHT - 154);
    }
}
// 开始查找按钮方法
- (void)targetQuery:(UIButton *)query
{
    [self.roadThread resignFirstResponder];
//http://www2.wzcx123.com/clients/android/1.1.php?time=1421986384&sign=6bf39048ad172d37020a3f692872adb6&alias=a954c6fd_cd68_4c50_a7df_8269f1c2934e&vehicles%5B0%5D%5Bvehicle%5D=鄂A7LT67&vehicles%5B0%5D%5Btype%5D=02&vehicles%5B0%5D%5BVIN%5D=102544&vehicles%5B0%5D%5BEIN%5D=&vehicles%5B0%5D%5Bareas%5D=湖北省
    NSString *tempStr = [self.roadThread.text stringByAppendingString:self.selectCity.titleLabel.text];
    [self.dataBase openDB];
    [self.dataBase createBusOfLine];
    [self.dataBase insertBusOfLine:self.roadThread.text city:self.selectCity.titleLabel.text combine:tempStr];
   
    
    [self firstPageSelect];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}
- (void)firstPageSelect
{
    if (self.roadThread.text.length != 0) {
        
        NSLog(@"%@", self.roadThread.text);
        NSString *path = [NSString stringWithFormat:@"http://apix.sinaapp.com/busline/?appkey=liming1234ou&city=%@&line=%@", self.selectCity.titleLabel.text, self.roadThread.text];
        
        [NetHander getDataWithUrl:path completion:^(NSData *data) {
            NSString *roadData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            self.roadArr = [roadData componentsSeparatedByString:@"\n\n"];
            
            [self.roadTableView reloadData];
        }];
    }else {
        alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"查询内容不能为空" delegate:self cancelButtonTitle:@"cancle" otherButtonTitles:@"OK", nil];
        [alert show];
    }
}

// 选择城市按钮方法
- (void)targetSelect:(UIButton *)selectCity
{
    [self.roadThread resignFirstResponder];

    CityViewController *city = [[CityViewController alloc] init];
    [city setCityBlock:^(NSString *str) {
        if([str hasSuffix:@"自治州"]) {
            str = [str substringToIndex:2];
        }else if ([str hasSuffix:@"地区"]){
            str = [str substringToIndex:str.length - 2];
        }
        [selectCity setTitle:str forState:UIControlStateNormal];
    }];
    [self presentViewController:city animated:YES completion:^{
        
    }];
//    [self.navigationController pushViewController:city animated:YES];
}
#pragma mark 第二页
- (void)secondPage
{
    // 创建tableview
    self.changeTableview = [[UITableView alloc]initWithFrame:CGRectMake(WIDTH, 90, WIDTH, HEIGHT - 154) style:UITableViewStyleGrouped];
    self.changeTableview.delegate = self;
    self.changeTableview.dataSource = self;
    self.changeTableview.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bus.jpg"]];
    [self.busScrollView addSubview:self.changeTableview];
    // 创建两个textfield
    self.from = [[UITextField alloc] initWithFrame:CGRectMake(WIDTH + 10, 0, (WIDTH - 40) / 2, 40)];
    self.from.placeholder = @"起点";
    self.from.borderStyle = UITextBorderStyleRoundedRect;
    [self.busScrollView addSubview:self.from];
    self.to = [[UITextField alloc] initWithFrame:CGRectMake(WIDTH * 3 / 2 + 10, 0, WIDTH / 2 - 20, 40)];
    self.to.placeholder = @"终点";
    self.to.borderStyle = UITextBorderStyleRoundedRect;
    [self.busScrollView addSubview:self.to];
    // 创建一个查找按钮
    self.changeQuery = [UIButton buttonWithType:UIButtonTypeSystem];
    self.changeQuery.frame = CGRectMake(WIDTH, 50, WIDTH, 40);
    [self.changeQuery setTitle:@"查询" forState:UIControlStateNormal];
    [self.busScrollView addSubview:self.changeQuery];
    [self.changeQuery addTarget:self action:@selector(targetChange:) forControlEvents:UIControlEventTouchUpInside];
    // 判断是否是从历史记录里穿过来的
    if (self.fromStation.length != 0) {
        [self.cancle removeFromSuperview];
        self.roadTableView.frame = CGRectMake(WIDTH, 90, WIDTH, HEIGHT - 154);
        self.from.text = self.fromStation;
        NSLog(@"== %@, %@", self.from.text, self.fromStation);
        self.to.text = self.toStation;
        self.segment.selectedSegmentIndex = 1;
        self.busScrollView.contentOffset = CGPointMake(WIDTH, 0);
        [self secondPageSelect];
    }
}
// 查询换乘
- (void)targetChange:(UIButton *)changeButton{
    [self.from resignFirstResponder];
    [self.to resignFirstResponder];
    if (self.from.text.length != 0 && self.to.text.length != 0) {
        NSString *tempStr = [[self.from.text stringByAppendingString:self.to.text] stringByAppendingString:self.selectCity.titleLabel.text];
        [self.dataBase openDB];
        [self.dataBase createBusOfChange];
        [self.dataBase insertBusOfFrom:self.from.text to:self.to.text city:self.selectCity.titleLabel.text combine:tempStr];
    }
    [self secondPageSelect];
}
- (void)secondPageSelect
{
    NSString *path = [NSString stringWithFormat:@"http://openapi.aibang.com/bus/transfer?city=%@&start_addr=%@&end_addr=%@&rc=0&count=100&with_xys=0&app_key=ccc75e982d8b3679708d7a5903a0e051&alt=json", self.selectCity.titleLabel.text, self.from.text, self.to.text];
//    NSLog(@"%@", path);
    [NetHander getDataWithUrl:path completion:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.roadThreads = [[dic objectForKey:@"buses"] objectForKey:@"bus"];
        //        NSLog(@"%@", [dic objectForKey:@"message"]);
        if (self.roadThreads.count == 0) {
            self.roadThreads = @[[dic objectForKey:@"message"]];
        }
        [self.changeTableview reloadData];
    }];
}
#pragma mark 第三页
- (void)thirdPage
{
    // 创建输入框
    self.plat = [[UITextField alloc] initWithFrame:CGRectMake(WIDTH * 2, 0, WIDTH / 2, 40)];
    self.plat.placeholder = @"请输入站点";
    self.plat.borderStyle = UITextBorderStyleRoundedRect;
    [self.busScrollView addSubview:self.plat];
    
    // 创建查询按钮
    self.platSelect = [UIButton buttonWithType:UIButtonTypeSystem];
    self.platSelect.frame = CGRectMake(WIDTH * 5 / 2, 0, WIDTH / 4, 40);
    [self.platSelect setTitle:@"查询" forState:UIControlStateNormal];
    [self.platSelect addTarget:self action:@selector(targetPlat:) forControlEvents:UIControlEventTouchUpInside];
    [self.busScrollView addSubview:self.platSelect];
    //创建tableview
    self.platTableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH * 2, 50, WIDTH, HEIGHT - 130) style:UITableViewStyleGrouped];
    self.platTableView.delegate = self;
    self.platTableView.dataSource = self;
    self.platTableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cow.jpg"]];
    [self.busScrollView addSubview:self.platTableView];
    if (self.station.length != 0) {
        [self.cancle removeFromSuperview];
        self.roadTableView.frame = CGRectMake(WIDTH * 2, 50, WIDTH, HEIGHT - 194);
        self.plat.text = self.station;
        self.segment.selectedSegmentIndex = 2;
        self.busScrollView.contentOffset = CGPointMake(WIDTH * 2, 0);
        [self thirdPageSelect];
    }
    
}
// 查找方法
- (void)targetPlat:(UIButton *)plat
{
    [self.plat resignFirstResponder];
    if (self.plat.text.length == 0) {
        alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"输入框不能为空" delegate:self cancelButtonTitle:@"cancle" otherButtonTitles:@"OK", nil];
        [alert show];
    }else {
        NSString *tempStr = [self.plat.text stringByAppendingString:self.selectCity.titleLabel.text];
        [self.dataBase openDB];
        [self.dataBase createBusOfStation];
        [self.dataBase insertBusOfStation:self.plat.text city:self.selectCity.titleLabel.text combine:tempStr];
        [self thirdPageSelect];
    }
}
- (void)thirdPageSelect
{
    NSString *path = [NSString stringWithFormat:@"http://openapi.aibang.com/bus/stats?city=%@&q=%@&app_key=ccc75e982d8b3679708d7a5903a0e051&alt=json", self.selectCity.titleLabel.text, self.plat.text];
    [NetHander getDataWithUrl:path completion:^(NSData *data) {
        id plat = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (![[plat objectForKey:@"result_num"] isEqualToString:@"0"]) {
            
            self.platArr = [[plat objectForKey:@"stats"] objectForKey:@"stat"];
        }else {
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"没有该站点", @"name", nil];
            self.platArr = @[dic];
        }
        [self.platTableView reloadData];
    }];
}

// 滚动scrollview结束时调用的方法
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.segment.selectedSegmentIndex = self.busScrollView.contentOffset.x / WIDTH;
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
}
// 点击segment实现的方法
- (void)targetSegment:(UISegmentedControl *)segment
{
    
//    NSLog(@"segment:%u", segment.selectedSegmentIndex);
    self.busScrollView.contentOffset = CGPointMake(segment.selectedSegmentIndex * WIDTH, 0);
}
//tableveiw方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.segment.selectedSegmentIndex == 0) {
        // 判断是否请求到数据
        if ([[self.roadArr firstObject] length] == 0) {
            return 0;
        }
        return self.roadArr.count / 2;
    }else if (self.segment.selectedSegmentIndex == 1 && tableView == self.changeTableview){
        
        return self.roadThreads.count;
    }else {
        return self.platArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.segment.selectedSegmentIndex == 0) {
        FirstPageCell *cell = [self.roadTableView dequeueReusableCellWithIdentifier:@"0502"];
        if (cell == nil) {
            cell = [[FirstPageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"0502"];
        }
        NSLog(@"%lu", self.roadArr.count);
        if (self.roadArr.count != 0) {
            
       
        // 根据数据特点，把线路名拿出来放到tableview上
        NSString *tempStr = [self.roadArr objectAtIndex:indexPath.row * 2];
        NSArray *tempArr = [NSArray array];
        tempArr = [tempStr componentsSeparatedByString:@"\n"];
        if (tempStr.length == 0) {
            tempArr = @[@"没有找到您要的数据，请稍后再试"];
        }
        cell.firstLable.text = [tempArr firstObject];
        }
        return cell;
    }else if (self.segment.selectedSegmentIndex == 1) {
        SecondPageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"0502"];
        if (cell == nil) {
            cell = [[SecondPageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"0502"];
        }
         NSString *tempStr = [NSString string];
        if (self.roadThreads.count != 1) {
            NSLog(@"%lu", self.roadThreads.count);
            
            NSArray *tempArr = [[[self.roadThreads objectAtIndex:indexPath.row] objectForKey:@"segments"] objectForKey:@"segment"];
           
            for (NSDictionary *tempDic in tempArr) {
                tempStr = [tempStr stringByAppendingString:[tempDic objectForKey:@"line_name"]];
            }
        }
        else {
            tempStr = [self.roadThreads objectAtIndex:0];
        }
        cell.secondPage.text = tempStr;
        return cell;
    }else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"0502"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"0502"];
        }if (self.platArr.count != 0) {
            
        cell.textLabel.text = [[self.platArr objectAtIndex:indexPath.row] objectForKey:@"name"];
        }
        return cell;
    }
    return nil;
}
// 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.segment.selectedSegmentIndex == 2) {
        return 44;
    }
    return 88;
}
// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.segment.selectedSegmentIndex == 0) {

    // 把点击的线路传到下一页
    RoadViewController *road = [[RoadViewController alloc] init];
    NSMutableArray *tempArr = [NSMutableArray array];
    [tempArr addObject:[self.roadArr objectAtIndex:indexPath.row * 2]];
    [tempArr addObject:[self.roadArr objectAtIndex:indexPath.row * 2 + 1]];
    
    
    road.roadArr = tempArr;
    [self presentViewController:road animated:YES completion:^{
        
    }];
//    [self.navigationController pushViewController:road animated:YES];
    }else if (self.segment.selectedSegmentIndex == 1)
    {
        // 跳向换乘详情
        ChangeController *change = [[ChangeController alloc] init];
        change.changeDetail = [[[self.roadThreads objectAtIndex:indexPath.row] objectForKey:@"segments"] objectForKey:@"segment"];
        [self presentViewController:change animated:YES completion:^{
            
        }];
//        [self.navigationController pushViewController:change animated:YES];
    }else {
        if (![[[self.platArr objectAtIndex:indexPath.row] objectForKey:@"name"] isEqualToString:@"没有该站点"]) {
            
        PlatViewController *platVC = [[PlatViewController alloc] init];
        platVC.platDic = [self.platArr objectAtIndex:indexPath.row];
        [platVC setRoad:^(NSString *str) {
            self.roadThread.text = str;
            self.segment.selectedSegmentIndex = 0;
            self.busScrollView.contentOffset = CGPointMake(0, 0);
            [self targetQuery:self.platSelect];
        }];
        [self presentViewController:platVC animated:YES completion:^{
                
        }];
//        [self.navigationController pushViewController:platVC animated:YES];
        }
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.roadThread resignFirstResponder];
    [self.plat resignFirstResponder];
    [self.from resignFirstResponder];
    [self.to resignFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
